package com.freewater.helloworld.utils;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;

import java.util.function.Consumer;

public class JpaUtils {
    // do some work in a session, performing correct transaction management
    public static void inSession(EntityManagerFactory factory, Consumer<EntityManager> work) {
        try (var entityManager = factory.createEntityManager()) {
            manageTransaction(entityManager, work);
        }
    }

    private static void manageTransaction(EntityManager entityManager, Consumer<EntityManager> work) {
        var transaction = entityManager.getTransaction();
        try {
            transaction.begin();
            work.accept(entityManager);
            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }
    }
}
